import { ConfigureService } from '@app/configure';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Inject, Injectable } from '@nestjs/common';
import { AliIotSubscribeClientService } from 'apps/ali-iot-subscribe-client/src/ali-iot-subscribe-client.service';
import { MqttClientService } from 'apps/mqtt-client/src/mqtt-client.service';
import { Cache, Store } from 'cache-manager';
import Redis from 'ioredis';
import { MqttClient } from 'mqtt';

type Client = {
  client:Redis
}


@Injectable()
export class DeviceMsgDispatchService {
  private wattingPublishMsg:Array<{topic:string, content:string}> = []
  private wattingPushListMsg:string[] = [];

  private mqtt:MqttClient;
  private chargeInfoListKey:string;


  constructor(
    @Inject(CACHE_MANAGER) private cacheManager: Cache<Client & Store>,
    private readonly config:ConfigureService,
    private readonly aliClient:AliIotSubscribeClientService,

    private readonly mqttClient:MqttClientService
  ){

    this.chargeInfoListKey = config.get('deviceMsgListKeys.chargeInfo')
  }

  start() {
    this.mqtt = this.mqttClient.client("mqtt://127.0.0.1:" + this.config.get('mqtt.port'))
    this.mqtt.on('connect', () => {
      if(this.wattingPublishMsg.length > 0) {
        while(true) {
          const msg = this.wattingPublishMsg.pop()
          if(!msg) break
          this.mqtt.publish(msg.topic, msg.content)
        }
      }
    })

    this.mqtt.on('error', () => {
      console.log('mqtt 链接失败')
    })

    
    this.cacheManager.store.client.on('ready', () => {
      if(this.wattingPushListMsg.length > 0) {
        while(true) {
          const content = this.wattingPushListMsg.pop()
          if(!content) break
          this.cacheManager.store.client.lpush(this.chargeInfoListKey, content)
        }
      }
    })


    this.cacheManager.store.client.on('error', () => {
      console.log('redis 链接失败')
    })    

    const config = this.config.get('alicloud')
    this.aliClient.connect({
      uid : config.uid,
      regionId : config.regionId,
      accessKey : config.accessKeyId,
      accessSecret : config.accessKeySecret,
      consumerGroupId : config.consumerGroupId,
      instanceId : config.instanceId
    }, (topic:string, content:string, messageId:string) => {
      try {
        const msg = JSON.parse(content)
        if(!msg) return
        
        //console.log(topic)


        if('type' in msg) { //设备上报的
          const type = msg.type
          if(type == 2 || type == 6 || type == 13 || type == 15) { //服务端开始充电设备回复, 服务端停止充电设备回复，充电结束设备自动上报 刷卡充电上报
            let message = JSON.stringify({topic : topic, msg : msg})
            if(this.cacheManager.store.client.status == 'ready') {
              this.cacheManager.store.client.lpush(this.chargeInfoListKey, message)
            }else {
              this.wattingPushListMsg.unshift(message)
            }
            
            return
          }

          
        }

        if(this.mqtt.connected) {
          this.mqtt.publish(topic, content)
        }else {
          this.wattingPublishMsg.unshift({topic, content})
        }

      } catch (error) {
        
      }

    })
  }
}
